package com.blr.service;

import com.blr.config.InfluxDBTemplate;
import com.blr.entity.Forecast;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ForecastServiceImpl implements ForecastService {

    private final String MEASUREMENT = "forecast";
    private final InfluxDBTemplate influxDBTemplate;

    @Autowired
    public ForecastServiceImpl(InfluxDBTemplate influxDBTemplate) {
        this.influxDBTemplate = influxDBTemplate;
    }

    @Override
    public void save(Forecast forecast) {
        influxDBTemplate.write(MEASUREMENT,
                forecast.getTags(),
                forecast.getFields(),
                forecast.getTime(),
                TimeUnit.MILLISECONDS);
    }

    @Override
    public List<Forecast> findAll() {
        return influxDBTemplate.query("select * from " + MEASUREMENT, Forecast.class);
//        //0.定义保存结果集合
//        List<Forecast> forecasts = new ArrayList<>();
//        QueryResult queryResult = influxDBTemplate.query("select * from " + MEASUREMENT);
//        //1.获取结果
//        List<QueryResult.Result> results = queryResult.getResults();
//        //2.遍历结果
//        results.forEach(result -> {
//            //3.获取 series
//            List<QueryResult.Series> seriesList = result.getSeries();
//            //4.遍历 series
//            seriesList.forEach(series -> {
//                //5.获取的所有列
//                List<String> columns = series.getColumns();
//                //6.获取所有值
//                List<List<Object>> values = series.getValues();
//                //7.遍历数据 获取结果
//                for (int i = 0; i < values.size(); i++) {
//                    Forecast forecast = new Forecast();
//                    for (int j = 0; j < columns.size(); j++) {
//                        String column = columns.get(j);
//                        Object val = values.get(i).get(j);
//                        if ("time".equals(column)) {
//                            forecast.setTime(Timestamp.from(ZonedDateTime.parse(String.valueOf(val)).toInstant()).getTime());
//                        } else {//注意: 返回结果无须在知道是 tags 还是 fields  认为就是字段和值 可以将所有字段作为 field 进行返回
//                            if (!ObjectUtils.isEmpty(val)) {
//                                forecast.getFields().put(column, val);
//                            }
//                        }
//                    }
//                    forecasts.add(forecast);
//                }
//            });
//        });
//        return forecasts;
    }


}
